package io.github.talelin.latticy.service.impl;

import cn.hutool.core.util.IdUtil;
import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.latticy.common.constant.Constant;
import io.github.talelin.latticy.service.TokenService;
import io.github.talelin.latticy.util.JedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_NAME = "token";

    @Override
    public String createToken() {
        String str = IdUtil.fastUUID();
        JedisUtils.set(str, str, Constant.Redis.EXPIRE_TIME_MINUTE);
        return str;
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)) {// header中不存在token
            if (StringUtils.isBlank(token)) {// header中不存在token
                token = request.getParameter(TOKEN_NAME);
                if (StringUtils.isBlank(token)) {// parameter中也不存在token
                    throw new ForbiddenException(10013);
                }
            }
        }
        if (!JedisUtils.exists(token)) {
            throw new ForbiddenException(18705);
        }
        Long del = JedisUtils.del(token);
        if (del <= 0) {
            throw new ForbiddenException(18705);
        }
    }

}
